/*
 *    Copyright (c) 2018-2025, boss All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the boss developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: boss
 */
package com.hopes.bizz.risk.setting.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hopes.bizz.risk.common.constant.RiskDicConstant;
import com.hopes.bizz.risk.common.constant.enums.RiskSysDictEnum;
import com.hopes.bizz.risk.setting.dto.RiskConfigLecExcelDTO;
import com.hopes.bizz.risk.setting.entity.RiskConfigLEntity;
import com.hopes.bizz.risk.setting.entity.RiskConfigLecEntity;
import com.hopes.bizz.risk.setting.mapper.RiskConfigLecMapper;
import com.hopes.bizz.risk.setting.service.RiskConfigLService;
import com.hopes.bizz.risk.setting.service.RiskConfigLecService;
import com.hopes.bizz.risk.setting.vo.RiskConfigLecExcelVO;
import com.hopes.bizz.risk.setting.vo.RiskLecIdentifyVO;
import com.hopes.boss.admin.api.resolver.DictResolver;
import com.hopes.boss.common.core.exception.BizException;
import com.hopes.boss.common.entity.ValidateImportBO;
import com.hopes.boss.common.excel.vo.ErrorMessage;
import lombok.RequiredArgsConstructor;
import org.jetbrains.annotations.Nullable;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * LEC评级结果设置
 *
 * @author pig
 * @date 2023-07-18 19:51:26
 */
@Service
@RequiredArgsConstructor
public class RiskConfigLecServiceImpl extends ServiceImpl<RiskConfigLecMapper, RiskConfigLecEntity> implements RiskConfigLecService {

    private final RiskConfigLService riskConfigLService;

    @Override
    public boolean save(RiskConfigLecEntity riskConfigLec) {
        if (null == riskConfigLec || null == riskConfigLec.getRiskLevel()) {
            throw new BizException("参数错误");
        }
        // 根据 riskLevel 查询是否存在
        final LambdaQueryWrapper<RiskConfigLecEntity> queryWrapper = Wrappers.<RiskConfigLecEntity>lambdaQuery().eq(RiskConfigLecEntity::getRiskLevel, riskConfigLec.getRiskLevel());
        final List<RiskConfigLecEntity> riskConfigLecEntityList = baseMapper.selectList(queryWrapper);
        if (CollUtil.isNotEmpty(riskConfigLecEntityList)) {
            throw new BizException("风险等级已存在！");
        }
        return baseMapper.insert(riskConfigLec) > 0;
    }

    @Override
    public boolean updateById(RiskConfigLecEntity riskConfigLec) {
        if (null == riskConfigLec || null == riskConfigLec.getId() || null == riskConfigLec.getRiskLevel()) {
            throw new BizException("参数错误");
        }
        // 根据 riskLevel 查询是否存在
        final LambdaQueryWrapper<RiskConfigLecEntity> queryWrapper = Wrappers.<RiskConfigLecEntity>lambdaQuery().eq(RiskConfigLecEntity::getRiskLevel, riskConfigLec.getRiskLevel()).ne(RiskConfigLecEntity::getId, riskConfigLec.getId());
        final List<RiskConfigLecEntity> riskConfigLecEntityList = baseMapper.selectList(queryWrapper);
        if (CollUtil.isNotEmpty(riskConfigLecEntityList)) {
            throw new BizException("风险等级已存在！");
        }
        return baseMapper.updateById(riskConfigLec) > 0;
    }


    @Override
    public RiskLecIdentifyVO initIdentifyData() {
        final RiskLecIdentifyVO riskLecIdentifyVO = new RiskLecIdentifyVO();
        riskLecIdentifyVO.setRiskLecConfigList(this.list());
        riskLecIdentifyVO.setRiskLevelList(DictResolver.getItemsByType(RiskSysDictEnum.risk_level));

        final LambdaQueryWrapper<RiskConfigLEntity> wrapper = Wrappers.<RiskConfigLEntity>lambdaQuery()
                .in(RiskConfigLEntity::getModuleCode, RiskDicConstant.MODULE_LEC_L, RiskDicConstant.MODULE_LEC_E, RiskDicConstant.MODULE_LEC_C);
        final List<RiskConfigLEntity> riskConfigLEntityList = riskConfigLService.list(wrapper);
        if (CollectionUtil.isNotEmpty(riskConfigLEntityList)) {
            final Map<String, List<RiskConfigLEntity>> listMap = riskConfigLEntityList.stream().collect(Collectors.groupingBy(RiskConfigLEntity::getModuleCode));
            riskLecIdentifyVO.setRiskLecLList(RiskLecIdentifyVO.entity2VO(listMap.get(RiskDicConstant.MODULE_LEC_L)));
            riskLecIdentifyVO.setRiskLecEList(RiskLecIdentifyVO.entity2VO(listMap.get(RiskDicConstant.MODULE_LEC_E)));
            riskLecIdentifyVO.setRiskLecCList(RiskLecIdentifyVO.entity2VO(listMap.get(RiskDicConstant.MODULE_LEC_C)));
        }
        return riskLecIdentifyVO;
    }

    @Override
    public Integer getLecRiskLevel(@Nullable Integer riskValue) {
        Integer riskLevel = null;
        if (null == riskValue) {
            return riskLevel;
        }
        final List<RiskConfigLecEntity> configLecEntityList = baseMapper.selectList(Wrappers.<RiskConfigLecEntity>lambdaQuery().orderByAsc(RiskConfigLecEntity::getRiskLevel));
        for (RiskConfigLecEntity riskConfigLec : configLecEntityList) {
            if (null == riskConfigLec.getLeftValue() && null != riskConfigLec.getRightValue()) {
                if (riskValue < riskConfigLec.getRightValue()) {
                    riskLevel = riskConfigLec.getRiskLevel();
                    break;
                }
            } else if (null != riskConfigLec.getLeftValue() && null != riskConfigLec.getRightValue()) {
                if (riskValue < riskConfigLec.getRightValue() && riskValue >= riskConfigLec.getLeftValue()) {
                    riskLevel = riskConfigLec.getRiskLevel();
                    break;
                }
            } else if (null != riskConfigLec.getLeftValue() && null == riskConfigLec.getRightValue()) {
                if (riskValue >= riskConfigLec.getLeftValue()) {
                    riskLevel = riskConfigLec.getRiskLevel();
                }
            }
        }
        return riskLevel;
    }


    @Override
    public ValidateImportBO<RiskConfigLecExcelDTO> validateImport(List<RiskConfigLecExcelDTO> excelDTOList) {
        ValidateImportBO<RiskConfigLecExcelDTO> bo = new ValidateImportBO<>();
        List<ErrorMessage> errorMessageList = new ArrayList<>();
        List<RiskConfigLecExcelDTO> saveList = new ArrayList<>(excelDTOList);
        int successNum = excelDTOList.size();
        int failedNum = 0;

        bo.setErrorMessages(errorMessageList);
        bo.setSaveList(saveList);
        bo.setSuccessNum(successNum);
        bo.setFailedNum(failedNum);
        return bo;
    }

    @Override
    public RiskConfigLecEntity importDtoToEntity(RiskConfigLecExcelDTO excelDto) {
        RiskConfigLecEntity entity= new RiskConfigLecEntity();
        BeanUtils.copyProperties(excelDto, entity);
        return entity;
    }

    @Override
    public RiskConfigLecExcelVO exportEntityToVo(RiskConfigLecEntity entity) {
        RiskConfigLecExcelVO excelVO = new RiskConfigLecExcelVO();
        BeanUtils.copyProperties(entity, excelVO);
        return excelVO;
    }


}
